package com.example.lib_data.bmob

import kotlin.random.Random

/**
 * 广告图片的管理器
 * 使用instance获取单例对象
 */
class AdvManager private constructor(){
    private val mBmobManager = BmobManager.getInstance()
    private var mAdvList = emptyList<Adv>()
    private var preLoadIndex = -1

    companion object{
        val instance:AdvManager by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
            AdvManager()
        }
    }

    /**
     * 加载广告图片url资源
     */
    fun loadAdvs(callback:(Boolean)->Unit = {}){
        mBmobManager.queryAdv(onEnd = {
            if (!it.isNullOrEmpty()){
                mAdvList = it
                callback(true)
            }else{
                callback(false)
            }
        })
    }

    /**
     * 随机获取一个Adv对象
     */
    fun getAdv():Adv?{
        if (mAdvList.isEmpty()) return null
        if (preLoadIndex == -1) {
            preLoadIndex = Random.nextInt(mAdvList.size)
        }
        return mAdvList[preLoadIndex]
    }
}